package com.admin.service;

import com.admin.util.CommonUtil;
import com.data.entity.Admin;
import com.data.entity.Role;
import com.data.entity.RoleUser;
import com.data.mapper.AdminMapper;
import com.data.mapper.RoleMapper;
import com.data.mapper.RoleUserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @描述 <>
 * @参数 $params$
 * @返回值 $return$
 * @创建人 WangGuanghua
 * @创建时间 $date$
 */
@Service
public class AdminService {
    @Resource
    private AdminMapper adminMapper;
    @Resource
    private RoleUserMapper roleUserMapper;
    @Resource
    private RoleMapper roleMapper;


    public List<Admin> listPage(Integer pageIndex, Integer pageSize) {
        if(pageIndex>0){
            pageIndex=(pageIndex-1)*pageSize;
        }
        return adminMapper.listPage(pageIndex,pageSize);
    }

    public int count() {
        return adminMapper.count();
    }


    public int edit(Admin editUser) {
        return adminMapper.updateById(editUser);
    }

    public Admin getByUsername(String username) {
        return adminMapper.getByUsername(username);
    }

    public void add(Admin admin) {
        admin.setPassword(CommonUtil.createPassword(admin.getUsername(),"000000"));
        adminMapper.insert(admin);
        if(!CommonUtil.isEmpty(admin.getRoleId())){
            //添加用户管理角色信息
            RoleUser roleUser=new RoleUser();
            roleUser.setRoleId(admin.getRoleId());
            roleUser.setAdminId(admin.getId());
            roleUserMapper.insert(roleUser);
        }
    }

    /**
     * 功能描述: <br>
     * 〈根据id删除用户〉
     * @Param: [id]
     * @Return: void
     * @Author: wgh
     * @Date: 2019/9/11 0011 15:49
     */
    @Transactional
    public void delete(Long id) {
         roleUserMapper.deleteAdminById(id);
         adminMapper.deleteById(id);
    }



    public Role getRole(String username) {
        Admin ad =new Admin();
        ad.setUsername(username);
        Admin admin = adminMapper.selectOne(ad);
        if(CommonUtil.isEmpty(admin)){
            return null;
        }
        Role role = roleMapper.get(admin.getRoleId());
        return role;
    }


    public String getPassword(String username) {
        Admin admin = adminMapper.selectByUsername(username);
        return admin.getPassword();
    }

    public Admin getAdmin(String username) {
        return adminMapper.selectByUsername(username);
    }


    //修改密码
    public int updatePwd(Long id, String password) {
        return adminMapper.updatePwd(id,password);
    }

    public Admin getById(Long id) {
        return adminMapper.selectAdminById(id);
    }
}
